package cn.pugle.ormtest.ebean;

import io.ebean.EbeanServer;
import io.ebean.EbeanServerFactory;
import io.ebean.config.ServerConfig;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @author tzp
 * @date 2017/12/22
 */
@Component
public class EbeanServerFactoryBean implements FactoryBean<EbeanServer> {

    @Autowired
    private DataSource dataSource;

    @Override
    public EbeanServer getObject() throws Exception {

        Properties properties = new Properties();
        properties.load(new ClassPathResource("ebean/ebean.properties").getInputStream());

        ServerConfig config = new ServerConfig();
        config.loadFromProperties(properties);
        config.setDataSource(dataSource);
//        config.setExternalTransactionManager(new SpringAwareJdbcTransactionManager());
        config.setDefaultServer(true);
        config.setRegister(true);

        return EbeanServerFactory.create(config);
    }

    @Override
    public Class<?> getObjectType() {
        return EbeanServer.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
